// Dashboard API 实现（使用模拟数据）

import type {
  SalesOverview,
  Contract,
  Project,
  TimeSeriesData,
  ContractQueryParams,
  ProjectQueryParams,
  TimeRange,
  ApiResponse
} from '@/types'
import type { DashboardAPI } from './api'
import {
  generateSalesOverview,
  generateContracts,
  generateProjects,
  generateMultiMetricTimeSeriesData
} from './mock-data'
import { delay, createSuccessResponse, createErrorResponse } from './api'

class DashboardAPIImpl implements DashboardAPI {
  private updateCallbacks: Set<(data: any) => void> = new Set()
  private updateInterval: number | null = null

  async getSalesOverview(): Promise<ApiResponse<SalesOverview>> {
    try {
      await delay(300) // 模拟网络延迟
      const data = generateSalesOverview()
      return createSuccessResponse(data)
    } catch (error) {
      return createErrorResponse('Failed to fetch sales overview')
    }
  }

  async getContracts(params?: ContractQueryParams): Promise<ApiResponse<Contract[]>> {
    try {
      await delay(200)
      let contracts = generateContracts(50)

      // 应用过滤条件
      if (params?.status) {
        contracts = contracts.filter(c => c.status === params.status)
      }
      if (params?.client) {
        contracts = contracts.filter(c => 
          c.client.toLowerCase().includes(params.client!.toLowerCase())
        )
      }
      if (params?.startDate) {
        contracts = contracts.filter(c => c.signDate >= params.startDate!)
      }
      if (params?.endDate) {
        contracts = contracts.filter(c => c.signDate <= params.endDate!)
      }

      // 应用分页
      const offset = params?.offset || 0
      const limit = params?.limit || 20
      const paginatedContracts = contracts.slice(offset, offset + limit)

      return createSuccessResponse(paginatedContracts)
    } catch (error) {
      return createErrorResponse('Failed to fetch contracts')
    }
  }

  async getProjects(params?: ProjectQueryParams): Promise<ApiResponse<Project[]>> {
    try {
      await delay(250)
      let projects = generateProjects(30)

      // 应用过滤条件
      if (params?.status) {
        projects = projects.filter(p => p.status === params.status)
      }
      if (params?.riskLevel) {
        projects = projects.filter(p => p.riskLevel === params.riskLevel)
      }
      if (params?.startDate) {
        projects = projects.filter(p => p.startDate >= params.startDate!)
      }
      if (params?.endDate) {
        projects = projects.filter(p => p.deadline <= params.endDate!)
      }

      // 应用分页
      const offset = params?.offset || 0
      const limit = params?.limit || 15
      const paginatedProjects = projects.slice(offset, offset + limit)

      return createSuccessResponse(paginatedProjects)
    } catch (error) {
      return createErrorResponse('Failed to fetch projects')
    }
  }

  async getTrendData(
    metric: string,
    timeRange: TimeRange
  ): Promise<ApiResponse<TimeSeriesData[]>> {
    try {
      await delay(200)
      
      // 计算天数
      const days = Math.ceil(
        (timeRange.end.getTime() - timeRange.start.getTime()) / (1000 * 60 * 60 * 24)
      )
      
      const data = generateMultiMetricTimeSeriesData([metric], days)
      
      // 过滤时间范围
      const filteredData = data.filter(
        d => d.timestamp >= timeRange.start && d.timestamp <= timeRange.end
      )

      return createSuccessResponse(filteredData)
    } catch (error) {
      return createErrorResponse('Failed to fetch trend data')
    }
  }

  subscribeToUpdates(callback: (data: any) => void): () => void {
    this.updateCallbacks.add(callback)

    // 如果这是第一个订阅者，启动更新定时器
    if (this.updateCallbacks.size === 1) {
      this.startUpdateInterval()
    }

    // 返回取消订阅函数
    return () => {
      this.updateCallbacks.delete(callback)
      
      // 如果没有订阅者了，停止更新定时器
      if (this.updateCallbacks.size === 0) {
        this.stopUpdateInterval()
      }
    }
  }

  private startUpdateInterval(): void {
    // 每 30 秒推送一次更新
    this.updateInterval = window.setInterval(() => {
      const updateData = {
        type: 'data-update',
        timestamp: new Date(),
        data: {
          salesOverview: generateSalesOverview()
        }
      }

      this.updateCallbacks.forEach(callback => {
        try {
          callback(updateData)
        } catch (error) {
          console.error('Error in update callback:', error)
        }
      })
    }, 30000)
  }

  private stopUpdateInterval(): void {
    if (this.updateInterval !== null) {
      clearInterval(this.updateInterval)
      this.updateInterval = null
    }
  }
}

// 导出单例实例
export const dashboardAPI = new DashboardAPIImpl()
